// stores/adminComment.js
import { defineStore } from 'pinia'
import {
    batchComment,
    batchProgress,
    batchDetails,
    batchList,
    batchDelete,
    batchDeletes,
    batchInfoUpdate,
    taskResume,
    exportSuccessCommentUrls,
    refreshData
} from '@/api/comment.js'

export const useCommentsStore = defineStore('comments', {
    state: () => ({
        urlList: [],
        formData: {
            commentContent: '',
            nickname: '',
            email: '',
            websiteUrl: ''
        },
        isLoading: false,
        message: '',
        res: false,
        batchId:'',
        currentBatch: null,
    }),

    actions: {
        setUrlList(urls) {
            this.urlList = urls
            this.message = `成功加载 ${urls.length} 个链接`
        },

        clearUrlList() {
            this.urlList = []
        },

        addUrl(urlData) {
            if (!this.validateUrlData(urlData)) {
                console.error('Invalid URL data format')
                return false
            }
            this.urlList.push(urlData)
            return true
        },

        clearForm() {
            this.urlList = []
            this.formData = {
                commentContent: '',
                nickname: '',
                email: '',
                websiteUrl: ''
            }
            this.message = ''
        },

        async sendBatchComments() {

            if (!this.urlList.length) {
                this.message = '请先上传链接列表'
                return
            }

            if (!this.formData.commentContent || !this.formData.nickname || !this.formData.email) {
                this.message = '请填写必要的评论信息'
                return
            }

            this.isLoading = true
            this.message = '正在发送评论...'

            // 修改这里：将 urlList 中的对象数组转换为字符串数组
            const requestData = {
                targetUrls: this.urlList.map(item => item.url), // 提取 url 字符串
                commentContent: this.formData.commentContent,
                nickname: this.formData.nickname,
                email: this.formData.email,
                websiteUrl: this.formData.websiteUrl
            }

            try {
                const response = await batchComment(requestData);

                this.message = `${response.data.message}`

                // 获取批次号
                const batchNo = response.data.batchNo;

                // 定期检查进度
                const checkProgress = setInterval(async () => {
                    const progress = await this.getBatchProgress(batchNo);
                    if (progress) {
                        this.message = `处理进度: ${progress.completed}/${progress.total}`;

                        if (progress.completed === progress.total) {
                            clearInterval(checkProgress);
                            this.message = '评论发送完成';
                        }
                    }
                }, 5000);

                return response.data
            } catch (error) {
                this.message = '评论发送失败: ' + error.message
                console.error('Error sending comments:', error)
            } finally {
                this.isLoading = false
            }
        },

        // 获取批量任务进度
        async getBatchProgress(batchNo) {
            try {
                const response = await batchProgress(batchNo)
                return response.data.data
            } catch (error) {
                this.message = '获取进度信息失败'
                return null
            }
        },

        // 获取批量任务详情
        async getBatchDetails(batchNo, params) {
            try {
                const response = await batchDetails(batchNo,params)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 获取批次任务
        async getBatchList(params) {
            try {
                const response = await batchList(params)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 刷新进度
        async dataRefresh(params) {
            try {
                const response = await refreshData(params)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 删除批次任务
        async deleteBatch(batchNo) {
            try {
                const response = await batchDelete(batchNo)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 批量删除批次任务
        async deleteBatches(batchNos) {
            try {
                const response = await batchDeletes(batchNos)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 批量删除批次任务
        async updateBatchInfo(batchNos, info) {
            try {
                const response = await batchInfoUpdate({
                    batchNos,
                    ...info
                })
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 批量删除批次任务
        async resumeTask(batchNo) {
            try {
                const response = await taskResume(batchNo)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        async getSuccessCommentUrls(batchNo) {
            try {
                const response = await exportSuccessCommentUrls(batchNo)
                return response.data
            } catch (error) {
                this.message = '获取任务详情失败'
                return null
            }
        },

        // 在 store 中添加验证函数
        validateUrlData(urlData) {
            return typeof urlData === 'object' &&
                typeof urlData.url === 'string' &&
                typeof urlData.status === 'string'
        },
    }
})